
<template>
  <div  v-loading.lock="loading" element-loading-text="拼命上传中...">
    <el-upload 
    v-if="canDelete"
    ref="upload"
    action="https://upload.qbox.me" 
    :show-file-list="showFileList" 
    :data="dataObj" 
    drag 
    :multiple="basicPackDefault.multiple"
    :before-upload="beforeUpload" 
    :on-success="uploadSuccess"
    :on-change="onChange"
    :auto-upload="true"
    :accept="basicPack.accept"
    :on-error="onError"
    :before-remove='remove'
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击选择图片</em></div>
    </el-upload>
    <el-button v-if="false" style="    margin-left: 10px;position: absolute;left: 230px;top: 30px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> 
    <el-progress v-if="progress" :percentage="percentage" :status="status"></el-progress>
    <ul  class="el-upload-list el-upload-list--picture" :id='id' >
       <li  v-if="qiniuImage.image_uri&&qiniuImage.image_uri.length<=0">暂无图片列表</li>
       <template  v-for="(item,index) in arr.image_uri" >
          <li  :key='item' class="el-upload-list__item is-success"  v-if="item != '' " style="width:16%;margin-right:5px;display:inline-block;">
             <img v-lazy="item" alt=""  class="el-upload-list__item-thumbnail"    @click="Viewer($event)" style="cursor:pointer">
             <template v-if="canDelete">
                    <label  class="el-upload-list__item-status-label">
                       <i class="el-icon-upload-success el-icon-check"></i>
                     </label>
                     <i  class="el-icon-close" @click="delImg(index)"></i>
             </template>  
          </li>
        </template>
    </ul>
  </div>
</template>
<script>

import { getToken } from '@/api/qiniu'
//import { Message } from 'element-ui'
import store from '@/store'
import qiNiuPrefix from 'config/qiNiuPrefix.js'
import Viewer from "static/viewer/viewer.js"
//import $ from 'jquery'

// 获取七牛token 后端通过Access Key,Secret Key,bucket等生成token
// 七牛官方sdk https://developer.qiniu.com/sdk#official-sdk
var timer;
var viewer;
export default{
   mounted(){
   
     this.id = this.qiniuImage.id;
    if(typeof(this.qiniuImage.image_uri)=='string' ){
       var defaultValue=this.qiniuImage;
       this.qiniuImage=defaultValue
       this.qiniuImage.image_uri=defaultValue.image_uri.split(',').notempty();
    }
    this.arr = this.qiniuImage ;
    // console.dir(this.qiniuImage.nav)
  },

  props:["qiniuImage",'packJson','canDelete','id',"nav"],
  computed: {
    basicPack: {
      get: function () {
        if(this.packJson){
          if(this.packJson.maxLength){
            this.basicPackDefault.maxLength=this.packJson.maxLength;
          }
          if(this.packJson.size){
            this.basicPackDefault.size=this.packJson.size;
          }
          if(this.packJson.accept){
            this.basicPackDefault.accept=this.packJson.accept;
          }
        }
        
        return this.basicPackDefault
      },
      set: function (v) {
        
      }
    }
  },
  data() { 
    return {
      dataObj: { token: ''},
      showFileList:false,
      basicPackDefault:{
        maxLength:9,   //最大图片数量
        multiple:true, //可否上传多张
        accept:"image/gif,image/jpeg,image/jpg,image/png",
        size:""
      },
      maxLengthPass:"false",
      //进度条参数
      progress:false,
      percentage:0,
      status:"",
      count:0,
      loading:false,
      arr:[] 
      
    }
  },
  methods: {   
    submitUpload() {
      this.$refs.upload.submit();
    },
    onError(){
         
      this.loading=false;
      getToken().then(response => { 
        const token = response.uptoken
        store.dispatch('SetQiNiuToken',token)
        _self._data.dataObj.token = token 
        resolve(true)
      }).catch(err => {
        console.log(err)
        reject(false)
      })
      this.$message.error('哎呀,网络君打了下盹，请重新上传!');
    },
    onChange(file, fileList){
      if(file.status=="ready"){
        if(this.qiniuImage.image_uri.length+fileList.length>(this.basicPack.maxLength)){//fileList.length+
            this.maxLengthPass=false;
        }else{
            this.maxLengthPass=true;
        }
      }
    },
    beforeUpload(response, file, fileList) {
      this.loading=true;
      if(this.maxLengthPass){
          var isLtM = response.size / 1024 / 1024 < (this.basicPack.size);//图片大小
          if (!isLtM) {
            this.$message.error('上传图片大小不能超过'+(this.basicPack.size)+'MB!');
            this.loading=false;
            return isLtM
          }
          else{
            const _self = this
            return new Promise((resolve, reject) => {
              if(!store.getters.qiNiuToken){
                  getToken().then(response => { 
                    const token = response.uptoken
                    store.dispatch('SetQiNiuToken',token)
                    //commit('SET_QINIUTOKEN', token)
                    _self._data.dataObj.token = token 
                    resolve(true)
                  }).catch(err => {
                    console.log(err)
                    reject(false)
                  })
               }else{
                _self._data.dataObj.token = store.getters.qiNiuToken
                resolve(true)
               }
            })
          }
      }else{
        this.loading=false;
        this.$message.error('最多上传'+(this.basicPack.maxLength)+'张图片!');
        return false
      }
    },
    uploadSuccess(response, file, fileList){
      this.count++;
      this.qiniuImage.image_uri.push(qiNiuPrefix+response.key);
      if(this.count==fileList.length){
        this.count=0;
        
        this.$refs.upload.uploadFiles=[];
      }
      // this.$message.success('上传成功');
      this.$nextTick(()=>{
        if(this.count===0){
          this.loading=false;
        }
      })
    }
    //图片预览部分的js
    ,Viewer(_this){
      if(_this.currentTarget.getAttribute('lazy')=="error"){
         this.$message.warning('失效的图片链接！')
        //  alert(1)
         return false;
      }
      if($('.viewer-container').length>0){
        // alert(2)
        var zIndex=document.getElementsByClassName('viewer-container')[0].style['z-index'];
        $('.viewer-close').click();
        viewer=null;
      }
      viewer=new Viewer(document.getElementById(this.id),{
        fullscreen:false,
        hide: function (){
          // alert(3)  
          viewer.update();
          viewer.destroy()
          },
          show:function(){
            viewer.update();
          }
        });
      setTimeout(()=>{
        if(zIndex==-1){
          if(document.interchange){
            document.interchange();
          }
        }
      },1000)
    },
    delImg(index){
      // var imageUrl = this.qiniuImage.image_uri;
      // if ( this.qiniuImage.image_uri.length > 0) { 
      //  this.qiniuImage.image_uri.splice(index,1) ;
      //   this.$refs.upload
      //   this.$message({
      //         type: 'success',
      //         message: '删除成功!'
      //     });
      // }

      var imageUrl = this.qiniuImage.image_uri;
      if ( this.arr.image_uri.length > 0) { 
          this.arr.image_uri.splice(index,1) 
          this.$refs.upload
          this.$message({
                type: 'success',
                message: '删除成功!'
            });
      }
      // console.dir(this.arr)
      this.$emit('setQiniu',this.arr);
    },
    remove(file, fileList){
      // console.dir(file)
      
    }
  },
 
 
}
</script>
<style scoped  >
  @import './../../../static/viewer/viewer.styl';
</style>
<style>
  .el-upload-list--text{display: none!important;}
</style>